import { createRouter } from 'vue-router'
import NProgress from '@/utils/progress'
import { useUserStore } from '@/stores/user'
import { useGlobalStore } from '@/stores/global'
import { getHistoryMode } from './utils'

const router = createRouter({
  history: getHistoryMode(import.meta.env.VITE_ROUTER_HISTORY),
  routes: [
    {
      path: '/',
      name: 'Login',
      component: () => import('@/views/login/index.vue'),
    },
    {
      path: '/chat/:guid(.*)*',
      name: 'Chat',
      component: () => import('@/views/chat/index.vue'),
    },
    {
      path: '/error',
      name: 'Error',
      component: () => import('@/views/error.vue'),
    },
    {
      path: '/:pathMatch(.*)',
      redirect: '/',
    },
  ],
})

// 路由访问检测
router.beforeEach(async (to, from, next) => {
  if (from.name !== to.name) {
    NProgress.start() // 进度条处理
  }

  const userStore = useUserStore()
  const cacheStore = useGlobalStore()

  // 禁止直接访问错误页面
  if (to.name === 'Error' && !cacheStore.hasPageError) {
    return next({ name: 'Chat' })
  }

  try {
    if (['Login', 'Chat'].includes(to?.name as string)) {
      if (userStore.isLogin) {
        if (to.name === 'Login') {
          // 已登录跳转到聊天页
          return next({ name: 'Chat' })
        }
        if (from.name !== to.name) {
          await userStore.refreshUserInfo() // 验证 token
        }
      } else {
        if (to.name === 'Chat') {
          userStore.clearUserInfo() // 未登录跳转到登录页
          return next({ name: 'Login' })
        }
      }
    }
    next() // 放行
  } catch (e) {
    window.console.error(e)
    cacheStore.setPageError({
      status: e.status ?? 500,
      message: e.message,
    })
    next({ name: 'Error' }) // 跳转到错误页面
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
